﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

/*
 * Author:Conis
 * Date:
 * Description:SQL语句中的比较单元
 */
namespace Conis.Squirrel.SqlBuilder
{
    public abstract class BaseCompareUnit<T> : ConditionUnit
    {
        /// <summary>
        /// 字段名称
        /// </summary>
        public string FieldName { get; set; }
        /// <summary>
        /// 比较
        /// </summary>
        public CompareOperator Compare { get; set; }
        /// <summary>
        /// 与字段比较的值
        /// </summary>
        public T Value { get; set; }

        /// <summary>
        /// 值是否为字段
        /// </summary>
        public bool ValueIsSafe { get; set; }

        /// <summary>
        /// SQL语句中的比较单元，例如：field = 'abc'，field1 > 10
        /// </summary>
        /// <param name="connector">连接器</param>
        /// <param name="fieldName">字段名称</param>
        /// <param name="compare">比较器</param>
        /// <param name="value">值</param>
        /// <param name="valueIsSafe">值是否安全</param>
        public BaseCompareUnit(Connector connector, string fieldName, CompareOperator compare, T value, bool valueIsSafe)
        {
            this.FieldName = fieldName;
            this.Compare = compare;
            this.Value = value;
            this.ValueIsSafe = valueIsSafe;
            this.Connector = connector;
        }

        /// <summary>
        /// 循环之前的
        /// </summary>
        protected override void LoopBefore()
        {
            string value = this.Value.ToString();
            if (!this.ValueIsSafe)
            {
                string paramValue;
                value = "@";
                value += Guid.NewGuid().ToString("N");
                //检查是事为Like
                switch (this.Compare)
                {
                    case CompareOperator.Like:
                        paramValue = string.Format("%{0}%", this.Value);
                        break;
                    case CompareOperator.StartLike:
                        paramValue = string.Format("%{0}", this.Value);
                        break;
                    case CompareOperator.EndLike:
                        paramValue = string.Format("{0}%", this.Value);
                        break;
                    default:
                        paramValue = this.Value.ToString();
                        break;
                }
                this.paramsList.Add(this.CreateParameter(value, paramValue));
            }

            //除了第一个条件，其它的条件需要加上连接符
            if (this.currentIndex != 0)
            {
                this.container.Append(this.Connector.ToSql());
            }
            this.container.Append(this.FieldName).Append(this.Compare.ToSql()).Append(value);
        }
    }
}
